<?php
namespace app\admin\controller;

use app\admin\BaseController;
use app\admin\model\AdminUser;
use think\facade\Session;

class Index extends BaseController
{
    /**
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $menu = new \app\admin\model\Menu();
        $tree = $menu->getTree();
        return view('index/index',['tree'=>$tree]);
    }

    /**

     */
    public function main(){


        return view('index/main');
    }

    /**
     * 个人信息
     */
    public function userInfo(){
        if($this->request->isAjax()){
            $post = $this->request->post();
            $post['id'] = Session::get(AdminUser::LOGIN_NAME)['id'];
            $data = [
                'qq' => $post['qq'],
                'email' => $post['email'],
                'desc' => $post['desc'],
                'address' => $post['address']
            ];
            $model = new AdminUser();
            $user = $model->find($post['id']);
            if($user){
                return $user->data($data)->save();
            }
            return false;
        }
        $uid = Session::get(AdminUser::LOGIN_NAME)['id'];
        return view('index/userinfo',['data'=>AdminUser::find($uid)]);
    }

    /**
     * 修改密码
     */
    public function updatePwd(){
        if($this->request->isAjax()){
            $type = $this->request->post('type');
            $password = $this->request->post('password');
            $userSession = AdminUser::getLoginUser();
            $user = AdminUser::find($userSession['id']);
            if($type == 'checkpwd'){
                if($user && AdminUser::encrypt($password) === $user->password){
                    return true;
                }
                return false;
            }

            if($type == 'updatepwd'){
                $new1 = $this->request->post('pwdnew');
                $new2 = $this->request->post('new_repeat');
                if($user){
                    if(AdminUser::encrypt($password) === $user->password){
                        if($new1 == $new2){
                            return $user->data(['password'=>AdminUser::encrypt($new1)])->save();
                        }
                    }
                }
                return false;
            }


        }

        $uid = Session::get(AdminUser::LOGIN_NAME)['id'];
        return view('index/updatepwd',['data'=>AdminUser::find($uid)]);
    }


    public function hello($name = 'ThinkPHP6')
    {
        return 'hello,' . $name;
    }


}
